package com.wanglin.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wanglin.reggie.common.CustomException;
import com.wanglin.reggie.entity.Category;
import com.wanglin.reggie.entity.Dish;
import com.wanglin.reggie.entity.Setmeal;
import com.wanglin.reggie.mapper.CategoryMapper;
import com.wanglin.reggie.service.CategoryService;
import com.wanglin.reggie.service.DishService;
import com.wanglin.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * CategoryServiceImpl
 *
 * @author 王林
 * @version 1.0
 * @description
 * @date 2025/5/29 02:32
 * @projectName reggie_take_out
 * @package com.wanglin.reggie.service.impl
 * @className com.wanglin.reggie.service.impl.CategoryServiceImpl
 * @copyright Copyright 2020 Theofanis, Wang Lin All rights reserved.
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    // 注入DishService
    @Autowired
    private DishService dishService;

    // 注入SetmealService
    @Autowired
    private SetmealService setmealService;

    // 重写remove方法
    @Override
    public void remove(Long id) {
        // 创建LambdaQueryWrapper对象，用于查询Dish表
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 设置查询条件，根据categoryId查询
        dishLambdaQueryWrapper.eq(Dish::getCategoryId, id);
        // 查询Dish表中符合条件的记录数
        int count1 = dishService.count(dishLambdaQueryWrapper);
        // 如果记录数大于0，说明当前分类下有关联的菜品，不能删除
        if (count1 > 0) {
            throw new CustomException("当前分类下关联了菜品，不能删除");
        }
        // 创建LambdaQueryWrapper对象，用于查询Setmeal表
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 设置查询条件，根据categoryId查询
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId, id);
        // 查询Setmeal表中符合条件的记录数
        int count2 = setmealService.count(setmealLambdaQueryWrapper);
        // 如果记录数大于0，说明当前分类下有关联的套餐，不能删除
        if (count2 > 0) {
            throw new CustomException("当前分类下关联了套餐，不能删除");
        }
        // 调用父类的方法，根据id删除记录
        super.removeById(id);
    }
}
